const fs = require("fs");
const multer = require("multer");
const utils = require('../utils')

const chunkPath = './chunks'
const uploadsPath = './uploads'
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, chunkPath)  //  上传文件保存的路径
  },
  filename: function (req, file, cb) {
    cb(null, 'chunks-' + file.originalname) //  上传文件的名称
  }
})
const multerServer = multer({ storage: storage }) //  上传文件的中间件

if (!fs.existsSync(chunkPath)) {
  fs.mkdirSync(chunkPath)
}

if (!fs.existsSync(uploadsPath)) {
  fs.mkdirSync(uploadsPath)
}

//  检查chunk
exports.checkChunk = (fileName) => {
  const chunkName = fileName ? `chunks-${fileName}` : ''
  debugger
  const dirFiles = fs.readdirSync(chunkPath)
  debugger
  const fileIndex = dirFiles.indexOf(chunkName)
  return fileIndex > -1;
}

//  上传切片
exports.uploadChunk = (file) => {
  return !!file
}

//  合并切片
exports.mergeChunk = (req) => {
  return new Promise((resolve, reject) => {

    const { hash } = req.body

    if (!hash) {
      reject('hash值不能为空')
    }
    //  读取文件夹下的所有chunk文件，然后合并
    const chunkName = `chunks-${hash}-`
    const dirFiles = fs.readdirSync(chunkPath)
    const chunks = dirFiles.filter((file) => file.includes(chunkName, 0))

    if (!chunks.length) {
      reject('切片文件不存在')
    }

    const writeStream = fs.createWriteStream(`${uploadsPath}/${hash}.${utils.getSuffix(chunks[0])}`)

    chunks.forEach(chunk => {
      writeStream.write(fs.readFileSync(`${chunkPath}/${chunk}`))
    })
    writeStream.end()

    // 处理流结束事件
    writeStream.on('finish', (event) => {
      console.log('文件写入成功！', writeStream.path.slice(1))
      resolve(writeStream.path.slice(1))
    });

    // 处理流错误事件
    writeStream.on('error', (err) => {
      // console.error('文件写入失败！', err)
      resolve(err || '文件写入失败')
    })
  })
}
